package cn.samler.diandi.api.controller;

import cn.samler.diandi.api.annotation.IgnoreTokenCheck;
import cn.samler.diandi.api.model.io.Response;
import cn.samler.diandi.api.model.io.request.user.Login;
import cn.samler.diandi.api.model.io.request.user.ResetPassword;
import cn.samler.diandi.api.model.io.request.user.ResetUsername;
import cn.samler.diandi.api.model.io.request.user.SendSMSForm;
import cn.samler.diandi.api.service.UserService;
import cn.samler.diandi.api.utils.ResponseBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户登录
     * <p>通过反射机制，使得不同登录类型的表单调用不同的service.login进行登录</p>
     *
     * @param form 登录表单
     * @return Response
     */
    @PostMapping("login")
    @IgnoreTokenCheck
    public Response login(@RequestBody @Valid Login form) {
        Response resp;
        try {
            Method method = userService.getClass().getMethod("login", form.getClass());
            resp = (Response) method.invoke(userService, form);
        } catch (NoSuchMethodException e) {
            log.warn("Not support login method. ");
            resp = new ResponseBuilder().failure().msg("不支持的登录方式").build();
        } catch (InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            log.error("login error: " + e);
            resp = new ResponseBuilder().failure().msg("服务器遇到错误").build();
        }

        return resp;
    }

    /**
     * 重置密码
     *
     * @param form 表单
     * @return Response
     */
    @PostMapping("reset_password")
    public Response resetPassword(@RequestBody @Valid ResetPassword form) {
        return userService.resetPassword(form);
    }

    /**
     * 重置用户名
     *
     * @param form 表单
     * @return Response
     */
    @PostMapping("reset_username")
    public Response resetUsername(@RequestBody @Valid ResetUsername form) {
        return userService.resetUsername(form);
    }

    /**
     * 发送验证码
     *
     * @param form 提交表单
     * @return Response
     */
    @PostMapping("send_sms")
    @IgnoreTokenCheck
    public Response sendSms(@RequestBody @Valid SendSMSForm form) {
        return userService.sendSMS(form);
    }

}
